package com.iot.service;

import com.alibaba.fastjson2.JSONObject;
import com.iot.dto.CommandRequestDTO;
import com.iot.mqtt.MqttHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iot.repository.DeviceCommandMapper;
import com.iot.entity.DeviceCommand;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DeviceCommandServiceImpl extends ServiceImpl<DeviceCommandMapper, DeviceCommand> implements DeviceCommandService {

    private final DeviceCommandMapper commandMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendCommand(CommandRequestDTO dto) {
        // 1. 构造命令
        DeviceCommand command = new DeviceCommand();
        Date now = new Date();
        command.setDeviceId(dto.getDeviceId());
        command.setCommandType(dto.getCommandType());
        command.setCommandPayload(dto.getCommandPayload());
        command.setStatus(0); // 待发送
        command.setCreatedTime(now);
        command.setSendTime(now);
        commandMapper.insert(command);

        // 2. 构造 MQTT topic
        String topic = String.format("device/%s/command", dto.getDeviceId());

        JSONObject json = new JSONObject();
        json.put("date", now.toString());
        json.put("commandId", command.getId());
        json.put("type", dto.getCommandType());
        json.put("payload", dto.getCommandPayload());

        MqttHelper.getInstance().send(topic, json.toJSONString());

        command.setStatus(1); // 已发送
        commandMapper.updateById(command);
        log.info("命令已下发到设备 {}: {}", dto.getDeviceId(), json);
    }
}
